<?php

App::uses('CompositeKeyModel', 'Model');

/**
 * OrganisationSetting Model
 *
 * @property Organisation $Organisation
 * @property SettingType $SettingType
 */
class OrganisationSetting extends CompositeKeyModel {
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $useDbConfig = "organisations";
    public $primaryKeys = array('id', 'organisation_id');
    
    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'Organisation' => array(
            'className' => 'Organisation',
            'foreignKey' => 'organisation_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'SettingType' => array(
            'className' => 'SettingType',
            'foreignKey' => 'setting_type_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public function getSetting($organisation_id, $setting_key) {
        return $this->find('first', array(
            'conditions' => array(
                'OrganisationSetting.organisation_id' => $organisation_id,
                'SettingType.name' => $setting_key
            )
        ));
    }

    public function getSettingType($setting_key) {
        return $this->SettingType->find('first', array(
            'conditions' => array(
                'SettingType.name' => $setting_key
            ),
            'recursive'=>-1
        ));
    }


    public function setSetting($organisation_id,$key,$value) {
        $settings_data = $this->getSetting($organisation_id,$key);
        if($settings_data){
            $id = $settings_data['OrganisationSetting']['id'];
            return $this->updateAll(
                array('OrganisationSetting.value' => $value),
                array('OrganisationSetting.id' => $id)
            );
        }
        else{//Create new record
            $setting_type = $this->getSettingType($key);
            $setting_id = $setting_type['SettingType']['id'];
            return $this->save(array(
                'organisation_id' => $organisation_id,
                'setting_type_id'=> $setting_id,
                'value' => $value
            ));
        }
    }

    
    public function createDefault($organisation_id) {
        $setting_types = ClassRegistry::init('SettingType')->find('all', array(
            'recursive' => -1
        ));
        
        $settings = array('OrganisationSetting' => array());
        
        foreach($setting_types as $type) {
            $settings['OrganisationSetting'][] = array(
                'organisation_id' => $organisation_id,
                'setting_type_id' => $type['SettingType']['id'],
                'value' => $type['SettingType']['default']
            );
        }
        
        return $this->saveAll($settings['OrganisationSetting']);
    }
}
